package com.hengxinguotong.zhihuichengjian.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.UserInfo;
import com.hengxinguotong.zhihuichengjian.utils.ActivityController;
import com.hengxinguotong.zhihuichengjian.utils.MD5Util;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.GradientTextView;
import com.lidroid.xutils.http.RequestParams;
import com.orhanobut.logger.Logger;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.InstrumentedActivity;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by Administrator on 2017/7/26.
 */

public class LoginActivity extends InstrumentedActivity
{

    @BindView(R.id.et_username)
    EditText et_username;
    @BindView(R.id.close_rl)
    RelativeLayout closeRl;
    @BindView(R.id.et_password)
    EditText et_password;
    @BindView(R.id.tv_login)
    TextView tv_login;
    @BindView(R.id.ll_try_use)
    LinearLayout llTryUse;
    @BindView(R.id.title_tv)
    GradientTextView title_tv;
    @BindView(R.id.version_tv)
    HXTextView versionTv;

    private boolean isTest = true;
    private LoginActivity loginActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
//        {
//            Window window = getWindow();
//            window.setStatusBarColor(getColor(R.color.bgColor));
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//        }
        setContentView(R.layout.activity_login);
        ActivityController.addActivity(this);
        ButterKnife.bind(this);
        loginActivity = this;
        initViewPager();

        if (Utils.isDebugVersion(this))
        {
            Utils.setServerUrl(this, "http://223.75.250.147:10081/escst_interface");
        } else
        {
            Utils.setServerUrl(this, "http://221.234.44.78:81/escst_interface");
        }
    }

    @Override
    public void onStart()
    {
        super.onStart();
        ActivityController.setCurrentActivity(this);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        JPushInterface.onResume(getApplicationContext());
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        JPushInterface.onPause(getApplicationContext());
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        ActivityController.removeActivity(this);
    }

    private void initViewPager()
    {
        int lightBlue = getResources().getColor(R.color.color_lightblue);
        int darkBlue = getResources().getColor(R.color.color_darkblue);
        title_tv.setColor(lightBlue, darkBlue);
        et_username.setText(SPUtil.getString(loginActivity, "userName"));
        et_username.addTextChangedListener(new MyTextWatcher());
        versionTv.setText("当前版本：" + Utils.getVersionName(this));
        String logout = getIntent().getStringExtra("logout");
        if (logout != null && logout.equals("logout"))
        {
            // 调用 Handler 来异步设置别名
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, ""));
        }
    }

    private long currentTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit()
    {
        if ((System.currentTimeMillis() - currentTime) > 2000)
        {
            Toast.makeText(getApplicationContext(), "再次点击退出", Toast.LENGTH_SHORT).show();
            currentTime = System.currentTimeMillis();
        } else
        {
            ActivityController.finishAll();
            System.exit(0);
        }
    }

    private class MyTextWatcher implements TextWatcher
    {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            if (start != before)
            {
                closeRl.setVisibility(View.VISIBLE);
            } else
            {
                closeRl.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable s)
        {

        }
    }

    @OnClick({R.id.tv_login, R.id.ll_try_use, R.id.close_rl, R.id.logo_img,R.id.version_tv})
    public void onClick(View view)
    {
        Intent intent = new Intent();
        switch (view.getId())
        {
            case R.id.tv_login:
                String userName = et_username.getText().toString();
                if (TextUtils.isEmpty(userName))
                {
                    Toast.makeText(loginActivity, "用户名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                String passWord = et_password.getText().toString();
                if (TextUtils.isEmpty(passWord))
                {
                    Toast.makeText(loginActivity, "密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                initLogin(userName, passWord);
                break;
            case R.id.ll_try_use:
//                intent.setClass(loginActivity, ForgetActivity.class);
                intent.setClass(loginActivity, TryUseActivity.class);
                startActivity(intent);
                break;
            case R.id.close_rl:
                et_username.setText("");
                et_password.setText("");
                break;
            case R.id.logo_img:
                if (Utils.isDebugVersion(this))
                {
                    intent.setClass(loginActivity, ChangeIPActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.version_tv:
                break;
        }
    }

    /*
     *获取登录个人信息
     */
    private void initLogin(String userName, String passWord)
    {
        JSONObject jsonObject = new JSONObject();
        try
        {
            jsonObject.put("userName", userName);
            jsonObject.put("userPassword", MD5Util.getMD5(userName + passWord));
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try
        {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        Utils.requestData("登录中 . . .", loginActivity, "/user/login/", params, new Utils.ListenerJson()
        {
            @Override
            public void onSuccess(String json)
            {
                try
                {
                    JSONObject object = new JSONObject(json);
                    String status = object.getString("status");
                    String msg = object.getString("msg");
                    if ("1".equals(status))
                    {
                        Gson gson = new Gson();
                        UserInfo UserInfo = gson.fromJson(json, UserInfo.class);
                        String userId = UserInfo.value.getUserId();
                        SPUtil.put(loginActivity, "userId", UserInfo.value.getUserId());
                        // 调用 Handler 来异步设置别名
                        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, userId));
//                        SPUtil.put(loginActivity, "workType", UserInfo.value.getPerson().getWorkType());
                        SPUtil.put(loginActivity, "level", UserInfo.value.getLevel());
                        if (UserInfo.value.getLevel() == 1)
                        {
//                            SPUtil.put(loginActivity, "areaName", UserInfo.value.getLevelName());
                            SPUtil.put(loginActivity, "cityId", UserInfo.value.getLevelId());
                        } else if (UserInfo.value.getLevel() == 2)
                        {
                            SPUtil.put(loginActivity, "areaName", UserInfo.value.getLevelName());
                            SPUtil.put(loginActivity, "areaId", UserInfo.value.getLevelId());
                        } else if (UserInfo.value.getLevel() == 3)
                        {
//                            SPUtil.put(loginActivity, "vedio_ip", UserInfo.value.getVideo().getIp());
//                            SPUtil.put(loginActivity, "vedio_port", UserInfo.value.getVideo().getPort());
//                            SPUtil.put(loginActivity, "vedio_username", UserInfo.value.getVideo().getUsername());
//                            SPUtil.put(loginActivity, "vedio_password", UserInfo.value.getVideo().getPassword());
                        }
                        SPUtil.put(loginActivity, "levelName", UserInfo.value.getLevelName());
                        SPUtil.put(loginActivity, "userName", UserInfo.value.getUserName());
                        SPUtil.put(loginActivity, "realName", UserInfo.value.getRealName());
                        SPUtil.put(loginActivity, "uuid", UserInfo.value.getUuid());
                        SPUtil.put(loginActivity, "orgId", UserInfo.value.getOrgId());
                        SPUtil.put(loginActivity, "constructionid", UserInfo.value.getLevelId());
                        SPUtil.put(loginActivity, "json", json);
                        getMenuList(UserInfo.value.getUserId());

                    } else if ("0".equals(status))
                    {
                        Toast.makeText(loginActivity, msg, Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e)
                {
                    e.printStackTrace();
                    Toast.makeText(loginActivity, "登录失败:" + e.toString(), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(String json)
            {
                try
                {
                    JSONObject object = new JSONObject(json);
                    String status = object.getString("status");
                    String msg = object.getString("msg");
                    Toast.makeText(loginActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e)
                {
                    e.printStackTrace();
                    Toast.makeText(loginActivity, "登录失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /*
     *获取首页菜单权限信息
     */
    private void getMenuList(String userId)
    {
        JSONObject jsonObject = new JSONObject();

        try
        {
            jsonObject.put("userId", userId);
        } catch (JSONException e)
        {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try
        {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        Utils.requestData(getResources().getString(R.string.loading), loginActivity, "/authority/queryMenuList/" + SPUtil.getString(loginActivity, "uuid"), params, new Utils.ListenerJson()
        {
            @Override
            public void onSuccess(String json)
            {
                SPUtil.put(loginActivity, "authority", json);
                Intent intent = new Intent();
                intent.setClass(loginActivity, MainActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onFailure(String json)
            {

            }
        });
    }

    String TAG = "JPush";
    private final TagAliasCallback mAliasCallback = new TagAliasCallback()
    {
        @Override
        public void gotResult(int code, String alias, Set<String> tags)
        {
            String logs;
            switch (code)
            {
                case 0:
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    Logger.d("Set tag and alias success!code=" + code + "alias=" + alias + "tags=" + tags);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(android.os.Message msg)
        {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };
}
